<?php

namespace app\admin\logic;

use app\admin\model\Coursechapter;
use app\admin\model\Coursechaptersection;
use app\admin\model\history\Date;
use app\admin\model\Question;
use app\common\exception\BusinessException;
use app\common\service\ExcelDataToQuestionJsonService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportQuestionLogic
{
    public function export($course_id, $paper_id)
    {
        // 获取题目映射信息
        $excelDataToJson = new ExcelDataToQuestionJsonService();
        $questionTypeDict = array_flip($excelDataToJson->getQuestionTypeMap());
        $excelKeyMaps = array_flip($excelDataToJson->getExcelKeyMap());

        // 获取所有题目
        $allQuestion = $this->getAllQuestion($course_id, $paper_id);
        if (!$allQuestion) {
            throw new BusinessException('无题目数据可导出');
        }

        // 导出表
        $outSpreadsheet = new Spreadsheet();
        $worksheet = $outSpreadsheet->getActiveSheet();
        $worksheet->setCellValue('A1', '题型（必填）');
        $worksheet->setCellValue('B1', '题干（选填）');
        $worksheet->setCellValue('C1', '题目（必填）');
        $worksheet->setCellValue('D1', '选项 A');
        $worksheet->setCellValue('E1', '选项 B');
        $worksheet->setCellValue('F1', '选项 C');
        $worksheet->setCellValue('G1', '选项 D');
        $worksheet->setCellValue('H1', '选项 E');
        $worksheet->setCellValue('I1', '选项 F');
        $worksheet->setCellValue('J1', '选项 G');
        $worksheet->setCellValue('K1', '选项 H');
        $worksheet->setCellValue('L1', '正确答案（必填）');
        $worksheet->setCellValue('M1', '解析（选填）');

        // 循环题目导出数据
        $baseRow = 2;
        foreach ($allQuestion as $item) {
            // 提取题目信息
            $questionData = json_decode($item['question_data'], true);

            // 题型
            $questionTypeName = $questionTypeDict[$item['question_type']] ?? '';
            if (empty($questionTypeName)) {
                continue;
                //throw new BusinessException('不支持的题目类型' . $item['question_type']);
            }
            $worksheet->setCellValue('A' . $baseRow, $questionTypeName);

            // 背景
            $worksheet->setCellValue('B' . $baseRow, '');

            // 题目标题
            $worksheet->setCellValue('C' . $baseRow, $questionData['questionAsk']);

            // 提取选项
            $answerOption = $questionData['answerOption'] ?? [];
            $worksheet->setCellValue('D' . $baseRow, $answerOption['A'] ?? '');
            $worksheet->setCellValue('E' . $baseRow, $answerOption['B'] ?? '');
            $worksheet->setCellValue('F' . $baseRow, $answerOption['C'] ?? '');
            $worksheet->setCellValue('G' . $baseRow, $answerOption['D'] ?? '');
            $worksheet->setCellValue('H' . $baseRow, $answerOption['E'] ?? '');
            $worksheet->setCellValue('I' . $baseRow, $answerOption['F'] ?? '');
            $worksheet->setCellValue('J' . $baseRow, $answerOption['G'] ?? '');
            $worksheet->setCellValue('K' . $baseRow, $answerOption['H'] ?? '');
            $worksheet->setCellValue('L' . $baseRow, $questionData['correctOption'] ?? '');
            $worksheet->setCellValue('M' . $baseRow, $questionData['explanation'] ?? '');
            $baseRow++;
        }

        // 循环设置列宽
        foreach ($excelKeyMaps as $key => $val) {
            $worksheet->getColumnDimension($key)->setWidth(20);
        }

        // 保存文件到服务器
        $writer = new Xlsx($outSpreadsheet);

        // 生成文件名称
        $title = '导出题目数据' . date('Y-m-d') . '.xlsx';
        $filePath = exportExcelAttachmentRealPath($title);
        $writer->save($filePath);
        return exportExcelAttachmentPath($title);
    }

    private function getAllQuestion($course_id, $paper_id)
    {
        // 查询题目数据
        $where = [];
        if ($course_id) {
            $where['course_id'] = ['in', $course_id];
        }
        if ($paper_id) {
            $where['extend_id'] = ['in', $paper_id];
        }
        $model = new Question();
        return $model->where($where)->select();
    }

    private function getAllSectionListData($course_id)
    {
        // 章节题库
        $where = [
            'course_id' => ['=', $course_id],
            'status' => ['=', 1],
        ];

        // 查询所有章编号
        $model1 = new Coursechapter();
        $chapterIds = $model1->where($where)->field('id')->column('id');
        if ($chapterIds) {

            // 查询所有节编号
            $where = ['pid' => ['in', $chapterIds], 'status' => 1];
            $model2 = new Coursechaptersection();
            $list = $model2->where($where)->select();
            return array_dict($list, 'id');
        }
        return [];
    }

    private function getAllHistoryDate($course_id)
    {
        $model = new Date();
        $where = [
            'course_id' => $course_id,
        ];
        $list = $model->where($where)->select();
        return array_dict($list, 'id');
    }

    private function saveQuestion($course_id, $saveType, $extend_id, $question)
    {
        // 组装到库的数据
        $saveData = $this->cleanQuestionData($course_id, $saveType, $extend_id, $question);

        // 新增数据
        $model = new Question();
        $questionId = $model->insertGetId($saveData);
        if (!$questionId) {
            throw new BusinessException('保存数据库失败');
        }
    }

    private function cleanQuestionData($course_id, $saveType, $extend_id, $question)
    {
        // 获取基础数据
        if ($saveType == 0) {
            $basicData = $this->getTypeAndExtendIdAndChargeType($course_id, $question);
        } else {
            $basicData = $this->getTypeAndExtendIdAndChargeTypeBySaveTypeAndExtendId($saveType, $extend_id);
        }

        // 组装数据
        $time = time();
        $saveData = [
            'type' => $basicData['type'],
            'course_id' => $course_id,
            'extend_id' => $basicData['extend_id'],
            'charge_type' => $basicData['charge_type'],
            'question_type' => $question['questionType'],
            'question_name' => $question['questionAsk'],
            'question_data' => $this->buildQuestionJson($question),
            'a_time' => $time,
            'u_time' => $time,
        ];
        return $saveData;
    }

    private function buildQuestionJson($question)
    {
        $data = [];
        $allKeys = ['questionAsk', 'answerOption', 'correctOption', 'explanation'];
        foreach ($allKeys as $key) {
            if (array_key_exists($key, $question)) {
                $data[$key] = $question[$key];
            }
        }
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * getTypeAndExtendIdAndChargeType
     * @param $course_id
     * @param $question
     * @return array|int[]
     * @throws BusinessException
     */
    private function getTypeAndExtendIdAndChargeType($course_id, $question)
    {
        // 提取参数
        $questionCategoryName = $question['questionCategoryName'] ?? '';

        // 免费题库
        if ($questionCategoryName == '免费') {
            return ['type' => 1, 'extend_id' => 0, 'charge_type' => 1];
        }

        // 高级题库
        if ($questionCategoryName == '高级') {
            return ['type' => 1, 'extend_id' => 0, 'charge_type' => 2];
        }

        // 章节题库
        $where = [
            'course_id' => ['=', $course_id],
            'status' => ['=', 1],
        ];
        $model1 = new Coursechapter();
        $chapterIds = $model1->where($where)->field('id')->column('id');
        if ($chapterIds) {
            $where = ['pid' => ['in', $chapterIds], 'status' => 1, 'name' => $questionCategoryName];
            $model = new Coursechaptersection();
            $extendId = $model->where($where)->value('id');
            if ($extendId) {
                return ['type' => 3, 'extend_id' => $extendId, 'charge_type' => 0];
            }
        }

        // 历年真题
        $model = new Date();
        $where = [
            'course_id' => ['=', $course_id],
            'name' => ['=', $questionCategoryName],
        ];
        $extendId = $model->where($where)->value('id');
        if ($extendId) {
            return ['type' => 2, 'extend_id' => $extendId, 'charge_type' => 0];
        }
        throw new BusinessException('请检查您的目录名称' . $questionCategoryName . '是否合法');
    }

    private function getTypeAndExtendIdAndChargeTypeBySaveTypeAndExtendId($saveType, $extend_id)
    {
        // 免费题库
        if ($saveType == 1) {
            return ['type' => 1, 'extend_id' => 0, 'charge_type' => 1];
        }

        // 高级题库
        if ($saveType == 2) {
            return ['type' => 1, 'extend_id' => 0, 'charge_type' => 2];
        }

        // 章节题库
        if ($saveType == 3) {
            return ['type' => 3, 'extend_id' => $extend_id, 'charge_type' => 0];
        }

        // 历年真题
        if ($saveType == 4) {
            return ['type' => 2, 'extend_id' => $extend_id, 'charge_type' => 0];
        }
        throw new BusinessException('不支持的目录类型' . $saveType);
    }

}